<template>
  <div class="register-view">
    <div class="register-container">
      <!-- 注册表单卡片 -->
      <el-card class="register-card" shadow="hover">
        <template #header>
          <div class="register-header">
            <h2 class="register-title">创建账号</h2>
            <p class="register-subtitle">加入GovernTalk，开启公考备考之旅</p>
          </div>
        </template>
        
        <!-- 注册表单 -->
        <el-form
          ref="registerFormRef"
          v-model="registerForm"
          :rules="registerRules"
          class="register-form"
        >
          <!-- 手机号输入 -->
          <el-form-item prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="请输入手机号码"
              prefix-icon="Mobile"
              :validate-event="false"
              @blur="registerFormRef?.validateField('phone')"
            />
          </el-form-item>

          <!-- 验证码输入 -->
          <el-form-item prop="verificationCode">
            <el-input
              v-model="registerForm.verificationCode"
              placeholder="请输入验证码"
              prefix-icon="Message"
              :validate-event="false"
              @blur="registerFormRef?.validateField('verificationCode')"
            >
              <template #append>
                <el-button @click="sendVerificationCode" :disabled="countdown > 0" class="send-code-btn">
                  {{ countdown > 0 ? `${countdown}秒后重新发送` : '获取验证码' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <!-- 密码输入 -->
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              placeholder="请设置密码"
              type="password"
              prefix-icon="Lock"
              show-password
              :validate-event="false"
              @blur="registerFormRef?.validateField('password')"
            />
          </el-form-item>

          <!-- 确认密码 -->
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              placeholder="请确认密码"
              type="password"
              prefix-icon="Lock"
              show-password
              :validate-event="false"
              @blur="registerFormRef?.validateField('confirmPassword')"
            />
          </el-form-item>

          <!-- 用户协议 -->
          <el-form-item prop="agreement">
            <el-checkbox v-model="registerForm.agreement" class="agreement-checkbox">
              我已阅读并同意
              <el-button type="text" class="agreement-link" @click="showAgreementModal('user')">《用户协议》</el-button>
              和
              <el-button type="text" class="agreement-link" @click="showAgreementModal('privacy')">《隐私政策》</el-button>
            </el-checkbox>
          </el-form-item>

          <!-- 注册按钮 -->
          <el-form-item>
            <el-button
                  type="primary"
                  class="register-button"
                  @click="handleRegister"
                  :loading="isLoading"
                  style="background-color: #409EFF; border-color: #409EFF; font-weight: bold;"
                >
                  <span v-if="!isLoading">立即注册</span>
                  <span v-else>注册中...</span>
                </el-button>
          </el-form-item>

          <!-- 登录提示 -->
          <div class="login-tip">
            <span>已有账号？</span>
            <el-button type="text" class="login-link" @click="handleLogin">立即登录</el-button>
          </div>

          <!-- 快速注册 -->
          <div class="quick-register">
            <div class="divider">
              <span>快速注册</span>
            </div>
            <div class="social-register">
              <el-button type="text" class="social-btn" @click="registerWithWechat">
                <el-icon class="social-icon"><Wechat /></el-icon>
                <span>微信</span>
              </el-button>
              <el-button type="text" class="social-btn" @click="registerWithQQ">
                <el-icon class="social-icon"><QQ /></el-icon>
                <span>QQ</span>
              </el-button>
              <el-button type="text" class="social-btn" @click="registerWithWeibo">
                <el-icon class="social-icon"><Weibo /></el-icon>
                <span>微博</span>
              </el-button>
            </div>
          </div>
        </el-form>
      </el-card>
    </div>

    <!-- 用户协议/隐私政策模态框 -->
    <el-dialog v-model="showAgreementModalVisible" :title="agreementModalTitle" width="600px" height="500px">
      <div class="agreement-content" v-html="agreementContent"></div>
      <template #footer>
        <el-button @click="showAgreementModalVisible = false">我知道了</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { register } from '@/api/auth';

const router = useRouter();

// 表单引用
const registerFormRef = ref<any>();

// 加载状态
const isLoading = ref(false);

// 验证码倒计时
const countdown = ref(0);

// 协议模态框
const showAgreementModalVisible = ref(false);
const agreementModalTitle = ref('');
const agreementContent = ref('');

// 注册表单数据
const registerForm = ref({
  username: '',
  email: '',
  nickname: '',
  phone: '',
  verificationCode: '',
  password: '',
  confirmPassword: '',
  agreement: false
});

// 注册表单验证规则
const registerRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  nickname: [
    { min: 2, max: 20, message: '昵称长度应在2到20个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度为4-6位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度应在6到30个字符之间', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value && !/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,30}$/.test(value)) {
          callback(new Error('密码必须包含大小写字母和数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: any) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
        trigger: 'blur'
    }
  ],
  agreement: [
    { required: true, message: '请阅读并同意用户协议和隐私政策', trigger: 'change' }
  ]
});

// 处理注册
const handleRegister = async () => {
  try {
    // 表单验证
    await registerFormRef.value.validate();
    
    isLoading.value = true;

    // 调用API注册
    await register({
      username: registerForm.value.username,
      email: registerForm.value.email,
      password: registerForm.value.password,
      nickname: registerForm.value.nickname
    });
    
    ElMessage.success('注册成功，请登录');
    router.push('/login');
  } catch (error: any) {
    console.error('注册失败', error);
    ElMessage.error(error.message || '注册失败，请重试');
  } finally {
    isLoading.value = false;
  }
};

// 处理登录跳转
const handleLogin = () => {
  router.push('/login');
};

// 发送验证码
const sendVerificationCode = () => {
  if (!registerForm.value.phone) {
    ElMessage.warning('请先输入手机号码');
    return;
  }

  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(registerForm.value.phone)) {
    ElMessage.warning('请输入正确的手机号码');
    return;
  }

  // 模拟发送验证码
  ElMessage.success('验证码已发送');
  
  // 开始倒计时
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 显示协议模态框
const showAgreementModal = (type: string) => {
  if (type === 'user') {
    agreementModalTitle.value = '用户协议';
    agreementContent.value = `
      <h3>用户协议</h3>
      <p>欢迎您使用GovernTalk服务！请您仔细阅读并理解本协议的全部内容。</p>
      <h4>一、服务内容</h4>
      <p>GovernTalk是一个专注于公务员考试备考的学习平台，提供题库、学习资料、学习小组等服务。</p>
      <h4>二、用户注册与账号安全</h4>
      <p>1. 您需要提供真实、准确的个人资料，并在资料变更时及时更新。</p>
      <p>2. 您应妥善保管账号和密码，对使用您账号的所有行为负责。</p>
      <h4>三、用户行为规范</h4>
      <p>1. 您不得利用本平台从事任何违法违规活动。</p>
      <p>2. 您不得发布任何侵犯他人知识产权、隐私权等合法权益的内容。</p>
      <h4>四、版权声明</h4>
      <p>本平台提供的所有内容仅供学习参考，未经授权不得用于商业目的。</p>
      <h4>五、其他条款</h4>
      <p>本协议的最终解释权归GovernTalk所有，如有变更将在平台公告。</p>
    `;
  } else {
    agreementModalTitle.value = '隐私政策';
    agreementContent.value = `
      <h3>隐私政策</h3>
      <p>GovernTalk非常重视用户隐私保护，我们将严格保护您的个人信息安全。</p>
      <h4>一、信息收集</h4>
      <p>1. 注册信息：包括您提供的手机号、昵称等。</p>
      <p>2. 使用信息：包括您的浏览记录、学习进度、搜索记录等。</p>
      <p>3. 设备信息：包括您使用的设备型号、操作系统、浏览器类型等。</p>
      <h4>二、信息使用</h4>
      <p>1. 提供服务：用于账户验证、提供个性化服务等。</p>
      <p>2. 改进服务：用于分析用户行为、优化产品体验等。</p>
      <p>3. 安全保障：用于预防和打击违法违规行为。</p>
      <h4>三、信息保护</h4>
      <p>我们采用加密技术、访问控制等措施保护您的个人信息安全。</p>
      <h4>四、信息共享</h4>
      <p>我们不会向第三方出售、出租您的个人信息，除非获得您的明确同意。</p>
      <h4>五、您的权利</h4>
      <p>您有权访问、更正、删除您的个人信息，也可以注销账号。</p>
    `;
  }
  showAgreementModalVisible.value = true;
};

// 社交媒体注册
const registerWithWechat = () => {
  ElMessage.info('微信注册功能待实现');
};

const registerWithQQ = () => {
  ElMessage.info('QQ注册功能待实现');
};

const registerWithWeibo = () => {
  ElMessage.info('微博注册功能待实现');
};
</script>

<style lang="scss" scoped>
.register-view {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-container {
  max-width: 400px;
  width: 100%;
}

.register-card {
  border-radius: 16px;
  overflow: hidden;
  background-color: white;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

.register-header {
  text-align: center;
  padding: 20px 0;
}

.register-title {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.register-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.register-form {
  padding: 0 40px 40px 40px;
}

.send-code-btn {
  padding: 0 15px;
  height: 100%;
}

.agreement-checkbox {
  font-size: 14px;
  color: #4b5563;
  margin-bottom: 20px;
}

.agreement-link {
  color: #6366f1;
  padding: 0 5px;
}

.register-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 8px;
  background-color: #6366f1;
  border: none;
  transition: all 0.3s;

  &:hover {
    background-color: #4f46e5;
  }

  &:active {
    transform: translateY(2px);
  }
}

.login-tip {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #4b5563;
}

.login-link {
  color: #6366f1;
  padding: 0 5px;
}

.quick-register {
  margin-top: 30px;
}

.divider {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  &::before,
  &::after {
    content: '';
    flex: 1;
    height: 1px;
    background-color: #e5e7eb;
  }

  span {
    padding: 0 15px;
    font-size: 14px;
    color: #9ca3af;
  }
}

.social-register {
  display: flex;
  justify-content: center;
  gap: 30px;
}

.social-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  color: #6b7280;
  transition: all 0.3s;

  &:hover {
    color: #6366f1;
    background-color: #f3f4f6;
    border-radius: 8px;
  }
}

.social-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.agreement-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 10px;

  h3 {
    font-size: 18px;
    font-weight: 600;
    margin: 0 0 10px 0;
    color: #1f2937;
  }

  h4 {
    font-size: 16px;
    font-weight: 600;
    margin: 15px 0 8px 0;
    color: #374151;
  }

  p {
    font-size: 14px;
    line-height: 1.6;
    color: #4b5563;
    margin: 5px 0;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .register-form {
    padding: 0 20px 30px 20px;
  }

  .register-title {
    font-size: 20px;
  }

  .social-register {
    gap: 20px;
  }
}
</style>